package com.java80.littlegame.service.gateway.websocket;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.java80.littlegame.common.base.data.GameUser;
import com.java80.littlegame.common.base.data.GameUserMgr;
import com.java80.littlegame.common.base.vertx.ServiceStatusHelper;
import com.java80.littlegame.common.base.vertx.VertxMessageHelper;
import com.java80.littlegame.common.consts.SystemConsts;
import com.java80.littlegame.common.msg.BaseMsg;
import com.java80.littlegame.common.msg.ProtoHelper;
import com.java80.littlegame.common.msg.ProtoList;
import com.java80.littlegame.service.gateway.session.ChannelManageCenter;
import com.java80.littlegame.service.gateway.session.ConnectSession;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class MessageHelper {
	final transient static Logger log = LoggerFactory.getLogger(MessageHelper.class);

	public static void dispatchMsg(BaseMsg msg) {
		String queueName = null;
		long userId = msg.getSenderUserId();
		GameUser gameUser = GameUserMgr.getGameUser(userId);
		switch (msg.getType()) {
		case ProtoList.MSG_TYPE_HALL:
			if (gameUser == null || StringUtils.isBlank(gameUser.getHallServiceId())) {
				queueName = ServiceStatusHelper.randServiceStatus(SystemConsts.SERVICE_TYPE_HALL).getServiceQueueName();
			} else {
				queueName = ServiceStatusHelper.findServiceStatus(gameUser.getHallServiceId()).getServiceQueueName();
			}
			break;
		case ProtoList.MSG_TYPE_GAME:
			if (gameUser == null) {
				return;
			}
			String gameServiceId = gameUser.getGameServiceId();
			if (StringUtils.isBlank(gameServiceId)) {
				queueName = ServiceStatusHelper.randServiceStatus(SystemConsts.SERVICE_TYPE_GAME).getServiceQueueName();
			} else {
				queueName = ServiceStatusHelper.findServiceStatus(gameUser.getGameServiceId()).getServiceQueueName();
			}
			break;
		default:

			break;
		}
		VertxMessageHelper.sendMessageToService(queueName, msg.toString());
	}

	public static void outMsg(BaseMsg msg) {
		MsgQueueHelper.getInstance().addMsg(msg);
	}

	public static void outMsgToClient(BaseMsg msg) {
		log.info("send to client:{}", msg);
		Channel channel = null;
		ConnectSession session = ChannelManageCenter.getInstance().getSession(msg.getRecUserId());
		if (session != null)
			channel = session.getChannel();
		if (channel == null) {
			channel = ChannelManageCenter.getInstance().getChannel(msg.getSessionId());
		}
		if (channel == null) {
			channel = ChannelManageCenter.getInstance()
					.getChannel(GameUserMgr.getGameUser(msg.getRecUserId()).getSessionId());
		}
		if (channel != null) {
			String object = ProtoHelper.parseObject(msg);
			TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame(object);
			channel.writeAndFlush(textWebSocketFrame);
		}
	}

}
